package com.amkai.aes.webservice.binary.objecthandler.inventory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.inventory.PurchaseOrderResult;
import com.amkai.aes.aescommon.service.binary.job.inventory.PurchaseOrdersJob;
import com.amkai.aes.aescommon.service.binary.job.inventory.PurchaseOrdersResult;
import com.amkai.aes.generatedbeans.inventory.purchasing.PurchaseOrder;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class PurchaseOrdersHandler implements JobObjectHandler<PurchaseOrdersJob,Serializable, PurchaseOrdersResult> {
	private static final String query = "select po from PurchaseOrder po where po.baseOrganization.id = :depid and po.statusWrapper.id = :poStatus";
	
	@Override
	public PurchaseOrdersResult process(PurchaseOrdersJob job, Serializable object) throws Exception {
		// TODO Auto-generated method stub
		PurchaseOrdersResult result= new PurchaseOrdersResult();
		ArrayList<PurchaseOrder> alpo = new ArrayList<PurchaseOrder>();
		SessionManager sm = SiteManager.Start();
		try {
			sm.openSession();
			Query q = sm.execute(query);
			q = q.setLong("depid", job.getModuleDepartment().getId());
			q = q.setInteger("poStatus", job.poStatus);
			List<PurchaseOrder> lpo = q.list();
			for (PurchaseOrder po : lpo) {
				if (po.getVendor()!= null){
					po.getVendor().getDescription();	
				}
				
				if (po.getStatus()!= null){
					po.getStatus().name();
				}
				alpo.add(po);
			}
			
		//	result.setOrders(alpo); 
			result.orders.addAll(alpo);
		} catch (Exception e) {
			throw e;
		} finally {
			sm.closeSession();
		}
		return result;
	}
	
}
